package com.nhutcm.trackingthief.receiver;

import java.io.File;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.telephony.TelephonyManager;

import com.nhutcm.trackingthief.R;
import com.nhutcm.trackingthief.network.TrackingThiefNetwork;
import com.nhutcm.trackingthief.service.GPSService;
import com.nhutcm.trackingthief.service.TrackingThiefService;
import com.nhutcm.trackingthief.utils.Constant;
import com.nhutcm.trackingthief.utils.InternetUtils;
import com.nhutcm.trackingthief.utils.PrefUtils;

/**
 * RECEIVE ALL TYPE OF RECEIVER
 * 
 * @author NhutCM
 */
public class TrackingThiefReceiver extends BroadcastReceiver {

	public static final String TAG = "com.nhutcm.trackingthief.receiver.TrackingThiefReceiver";
	public static final String TRACKING_THIEF_RECEIVER = "com.nhutcm.trackingthief.intentservice.TrackingThiefReceiver.PROCESS_RESPONSE";
	public static final String TASK_TYPE = "action_type";
	public static final String FILE_PATH = "file_path";

	@Override
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(
				TrackingThiefReceiver.TRACKING_THIEF_RECEIVER)) {

			/** Nhận thông báo cần up hình lên mail */
			int task_type = intent.getExtras().getInt(TASK_TYPE);
			switch (task_type) {
			case Constant.TASK_CAPTURE_PHOTO_THIEF_COMPLETE:
				sendImageToEmail(context);
				break;

			case Constant.TASK_UPLOAD_COMPLETE:
				break;

			default:
				break;
			}
		} else if (intent.getAction().equals(
				ConnectivityManager.CONNECTIVITY_ACTION)) {

			if (InternetUtils.isConnectingToInternet(context)) {
				/** Get current location */
				sendAddressToEmail(context);

				/** Kết nối internet, upload hình ngay lập tức */
				sendImageToEmail(context);
			}
			/**
			 * Start service capture image
			 */
			startServiceCaptureImage(context);

		} else if (intent.getAction().equals(
				"android.intent.action.BOOT_COMPLETED")) {

			/** Nhận thông báo kiểm tra Sim có thay đổi hay không */
			doAfterBootComplete(context);
		} else if (intent.getAction().equals(
				"android.media.VOLUME_CHANGED_ACTION")) {

//			/* Code for test */
//			Toast.makeText(context, "Volume change", Toast.LENGTH_SHORT).show();
//			PrefUtils.saveStringToPreference(context,
//					context.getString(R.string.phone_state), "0");
//
//			PrefUtils.saveStringToPreference(context,
//					context.getString(R.string.pref_phone_serial_number),
//					"123456789");
//
//			SharedPreferences sharedPrefs;
//			sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context
//					.getApplicationContext());
//
//			sharedPrefs
//					.edit()
//					.putBoolean(
//							context.getApplicationContext().getString(
//									R.string.pref_phone_update_state_key),
//							false).commit();

		}
	}

	private void sendAddressToEmail(final Context context) {

		String statusPhone = PrefUtils.readStringFromPreference(
				context.getApplicationContext(),
				context.getString(R.string.phone_state));
		if (statusPhone.equals("0")) {
			GPSService gps = new GPSService(context);
			gps.getAddressAndSendToEmail();
		}

	}

	/**
	 * Duyệt danh sách hình chưa up và upload lên mail
	 * 
	 * @param context
	 */
	private void sendImageToEmail(Context context) {

		String fileDirsPath = PrefUtils.readStringFromPreference(context,
				context.getString(R.string.file_path));

		File file = new File(fileDirsPath);
		if (file.isDirectory()) {
			int numberFile = file.listFiles().length;
			for (int i = numberFile - 1; i >= 0; i--) {
				File f = file.listFiles()[i];

				Intent intent = new Intent(context, TrackingThiefNetwork.class);
				intent.putExtra(FILE_PATH, f.getPath());
				context.startService(intent);

			}
		}
	}

	/**
	 * Chi chup hinh khi so luong anh trong thu muc Files < MAX_NUMBER_FILE
	 * 
	 * @param context
	 */

	private void startServiceCaptureImage(Context context) {
		String fileDirsPath = PrefUtils.readStringFromPreference(context,
				context.getString(R.string.file_path));

		File file = new File(fileDirsPath);
		if (file.isDirectory()) {
			int numberFile = file.listFiles().length;
			if (numberFile < Constant.MAX_NUMBER_FILE) {
				context.startService(new Intent(context,
						TrackingThiefService.class));
			}
		}
	}

	/**
	 * Hàm trả về true nếu đúng Sim, false nếu Sim khác Sim ban đầu
	 * 
	 * @param context
	 * @return
	 */
	private boolean checkSimSerialNumber(Context context) {
		TelephonyManager telemamanger = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String simSerialNumber = telemamanger.getSimSerialNumber();

		String serialSim = PrefUtils.readStringFromPreference(context,
				context.getString(R.string.pref_phone_serial_number));

		if (serialSim.equals(simSerialNumber)) {
			return true;
		}
		return false;
	}

	/**
	 * Kiểm tra tình trạng điện thoại còn hay mất
	 * 
	 * @param context
	 */

	private void doAfterBootComplete(Context context) {

		if (!checkSimSerialNumber(context)) {

			/** Cập nhật trạng thái mất điện thoại */
			PrefUtils.saveStringToPreference(context,
					context.getString(R.string.phone_state), "0");

		} else {
			PrefUtils.saveStringToPreference(context,
					context.getString(R.string.phone_state), "1");

		}

		/** Mở service chụp hình */
		context.startService(new Intent(context, TrackingThiefService.class));
	}

}
